package com.rock.code.common.comm;

import com.p6spy.engine.logging.Category;
import com.p6spy.engine.spy.appender.StdoutLogger;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * The type P6spy logger.
 *
 * @author kongqiang
 * @date 2018 /02/08
 */
public class P6SpyLogger extends StdoutLogger {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());


    /**
     * 重写输出方法
     *
     * @param connectionId 连接id
     * @param now          当前时间
     * @param elapsed      执行时长，包括执行 SQL 和处理结果集的时间(可以参考来调优)
     * @param category     语句分类，statement、resultset 等
     * @param prepared     查询语句。可能是 prepared statement，表现为 select * from table1 where c1=?，问号参数形式
     * @param sql          含参数值的查询语句，如 select * from from table1 where c1=7
     */
    @Override
    public void logSQL(int connectionId, String now, long elapsed, Category category, String prepared, String sql) {
        if (!Category.COMMIT.equals(category)) {
            this.logText(this.strategy.formatMessage(connectionId, now, elapsed, category.toString(), "-prepared-", sql));
        }

    }

    @Override
    public void logText(String text) {
        StringBuilder sb = new StringBuilder();
        //匹配到最后一个|作为分隔符
        String[] arrString = text.split("\\|-prepared-\\|");
        if (arrString.length > 1) {
            String[] info = arrString[0].split("\\|");
            if (Category.STATEMENT.equals(new Category(info[2]))) {
                sb.append("SQL execute time (ms): " + info[1]);
                String sql = arrString[1].trim();
                if (StringUtils.isNotBlank(sql)) {
                    sql = new SQLFormatter().format(arrString[1]);
                    sb.append("\n");
                    sb.append(sql);
                    sb.append("\n");
                }
                logger.info(sb.toString());
            } else {
                sb.append(arrString[1]);
                logger.info(sb.toString());
            }
        } else {
            logger.info(text);
        }
    }

}
